package com.cnunicom.modules.tra.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.executor.ExcelWriteExecutor;
import com.alibaba.excel.write.merge.LoopMergeStrategy;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.cnunicom.common.excel.RecordMergeStrategy;
import com.cnunicom.common.utils.DateUtils;
import com.cnunicom.common.utils.PageUtils;
import com.cnunicom.common.utils.R;
import com.cnunicom.modules.tra.dto.ExportDTO;
import com.cnunicom.modules.tra.dto.ExportReqDTO;
import com.cnunicom.modules.tra.entity.RecordEntity;
import com.cnunicom.modules.tra.service.RecordService;
import com.cnunicom.modules.tra.vo.RewardVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 住房记录表
 *
 * @author dzygod
 * @email dingziyuan0@gmail.com
 * @date 2020-01-29 18:29:53
 */
@RestController
@RequestMapping("tra/record")
public class RecordController {
    @Resource
    private RecordService recordService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("tra:record:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = recordService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("tra:record:info")
    public R info(@PathVariable("id") Integer id){
		RecordEntity record = recordService.getById(id);

        return R.ok().put("record", record);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("tra:record:save")
    public R save(@RequestBody RecordEntity record){
//		recordService.save(record);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("tra:record:update")
    public R update(@RequestBody RecordEntity record){
		recordService.updateById(record);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("tra:record:delete")
    public R delete(@RequestBody Integer[] ids){
		recordService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 导出
     */
    @RequestMapping("/exportExcel")
    @RequiresPermissions("tra:record:export")
    public void exportExcel(@RequestBody ExportReqDTO exportReqDTO,HttpServletResponse httpServletResponse)
            throws IOException {

        httpServletResponse.setCharacterEncoding("UTF-8");
        String today = LocalDate.now().format(DateTimeFormatter.ofPattern(DateUtils.DATE_PATTERN));
        String fileName = URLEncoder.encode("住房信息统计表-" + today, "UTF-8");
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        httpServletResponse.setHeader("content-disposition", "attachment;filename=" + fileName +".xlsx");

        Map<String, List<ExportDTO>> reMap = recordService.excelExport(exportReqDTO);

        //获取根目录
        ClassPathResource resource = new ClassPathResource("static/exportTemplates.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(httpServletResponse.getOutputStream())
                .withTemplate(resource.getInputStream())
                .build();

        // 单位
        HashMap<String, String> unitMap = new HashMap<>();
        unitMap.put("startDate", exportReqDTO.getUnitPeriod().get(0));
        unitMap.put("endDate", exportReqDTO.getUnitPeriod().get(1));

        WriteSheet writeSheet0 = EasyExcel.writerSheet(0).build();
        excelWriter.fill(reMap.get("unit"), writeSheet0);
        excelWriter.fill(unitMap, writeSheet0);

        // 会员
        HashMap<String, String> staffMap = new HashMap<>();
        staffMap.put("startDate", exportReqDTO.getStaffPeriod().get(0));
        staffMap.put("endDate", exportReqDTO.getStaffPeriod().get(1));

        WriteSheet writeSheet1 = EasyExcel.writerSheet(1).build();
        excelWriter.fill(reMap.get("staff"), writeSheet1);
        excelWriter.fill(staffMap, writeSheet1);

        // 餐厅
        HashMap<String, String> resMap = new HashMap<>();
        resMap.put("startDate", exportReqDTO.getResPeriod().get(0));
        resMap.put("endDate", exportReqDTO.getResPeriod().get(1));

        WriteSheet writeSheet2 = EasyExcel.writerSheet(2).build();
        excelWriter.fill(reMap.get("res"), writeSheet2);
        excelWriter.fill(resMap, writeSheet2);

        // 总服务台
        HashMap<String, String> frontMap = new HashMap<>();
        frontMap.put("startDate", exportReqDTO.getFrontPeriod().get(0));
        frontMap.put("endDate", exportReqDTO.getFrontPeriod().get(1));

        WriteSheet writeSheet3 = EasyExcel.writerSheet(3).build();
        excelWriter.fill(reMap.get("front"), writeSheet3);
        excelWriter.fill(frontMap, writeSheet3);

        excelWriter.finish();

        /*EasyExcel.write(httpServletResponse.getOutputStream(), RecordEntity.class)
                .sheet("住房信息统计")
                .doWrite(data);*/
    }

    /**
     * 设置奖励金额
     */
    @RequestMapping("/reward")
    @RequiresPermissions("tra:record:reward")
    public R setUpReward (@RequestBody ExportReqDTO reward) {
        recordService.excelExport(reward);
        return R.ok();
    }

    /**
     * 获得奖励信息
     */
    @RequestMapping("/rewardInfo")
    @RequiresPermissions("tra:record:rewardInfo")
    public R rewardInfo() {
        RewardVO vo = recordService.rewardInfo();
        return R.ok().put("list",vo);
    }


}
